<template>
  <div class="app-container">
    <div class="serach-container">
      <div class="search-inputs">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline" label-position="right" label-width="70px">
          <el-form-item label="围栏名称">
            <el-input v-model="simpleForm.fenceName" placeholder="请输入围栏名称" />
          </el-form-item>
          <el-form-item v-show="activeIndex == 0" label="省份">
            <el-select v-model="simpleForm.provinceCode" filterable clearable placeholder="请选择省份" @change="simpleForm.cityCode = '', $forceUpdate()">
              <el-option v-for="(item, index) in provinceOptions" :key="index + '_' + item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="activeIndex == 0" label="城市">
            <el-select v-model="simpleForm.cityCode" filterable clearable placeholder="请选择城市" @change="$forceUpdate()">
              <el-option v-for="(item, index) in cityOptions" :key="index + '_' + item.cityCode" :label="item.cityName" :value="item.cityCode" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
      </div>
    </div>
    <div class="section-container">
       <el-tabs v-model="activeIndex" @tab-click="toggleTbas(activeIndex)">
        <!-- 行政区域围栏 -->
        <el-tab-pane label="行政区域围栏" :name="0">
          <transition name="fade-transform" mode="out-in">
             <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column v-for="item in tables.columns" :key="item.key" align="center" :show-overflow-tooltip="true" :width="item.width" :label="item.lable" header-align="center">
                <template slot-scope="{row}">
                  <div v-if="item.key === 'fenceStatus'">
                    <el-switch v-model="row.fenceStatus" :active-value="1" :inactive-value="0" @change="toggleStatus(row)" />
                  </div>
                  <span v-else-if="item.key === 'fenceType'">{{ row.fenceType ? '圆形' : '行政区域' }}</span>
                  <span v-else>{{ row[item.key] }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="160" fixed="right">
                <template slot-scope="{row}">
                  <el-button
                    type="text"
                    size="small"
                    @click="handelEdit(row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handelDelete(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
          </transition>
        </el-tab-pane>
        <!-- 无出行中心围栏 -->
        <el-tab-pane label="圆形围栏" :name="1">
          <transition name="fade-transform" mode="out-in">
             <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column label="围栏名称" prop="fenceName" align="center" />
              <el-table-column label="围栏类型" prop="fenceType" align="center">
                <template slot-scope="{row}">
                  <span>{{ row.fenceType ? '圆形' : '行政区域' }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="mainFenceAddress"
                label="无出行中心店名称"
                max-width="200">
                <template slot-scope="scope">
                  <span v-if="scope.row.mainFenceAddress && scope.row.mainFenceAddress.length > 20">
                    <el-popover placement="top-start" title="" max-width="800" trigger="hover" popper-class="workorder-problem-desc">
                      <div>{{ scope.row.mainFenceAddress }}</div>
                      <span slot="reference">
                        {{ scope.row.mainFenceAddress.substr(0,20) + '...' }}
                      </span>
                    </el-popover>
                  </span>
                  <span v-else>{{ scope.row.mainFenceAddress }}</span>
                </template>
              </el-table-column>
              <el-table-column label="围栏描述" width="200" :show-overflow-tooltip="true" prop="mainFenceRemark" align="center" />
              <el-table-column label="状态" prop="fenceStatus" align="center">
                <template slot-scope="{row}">
                  <el-switch v-model="row.fenceStatus" :active-value="1" :inactive-value="0" @change="toggleStatus(row)" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="{row}">
                  <el-button
                    type="text"
                    size="small"
                    @click="handelEdit(row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handelDelete(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </transition>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { queryFenceList, deleteFence, switchFence } from '@/api/crossRegionalMonitoring'
import Pagination from '@/components/Pagination'
import { getStorageByKey, unique_arr_by_key } from '@/utils/public'
export default {
  name: 'FenceList',
  components: { Pagination },
  data() {
    return {
      tables: {
        columns: [
          { lable: '围栏名称', key: 'fenceName', width: '180px', align: 'center' },
          { lable: '围栏类型', key: 'fenceType', align: 'center' },
          { lable: '围栏1位置', key: 'mainFenceAddress', width: '250px', align: 'center' },
          { lable: '围栏1描述', key: 'mainFenceRemark', width: '250px', align: 'center' },
          { lable: '围栏2位置', key: 'auxiliaryFenceAddress', width: '250px', align: 'center' },
          { lable: '围栏2描述', key: 'auxiliaryFenceRemark', width: '250px', align: 'center' },
          { lable: '省份', key: 'provinceName', align: 'center' },
          { lable: '城市', key: 'cityName', align: 'center' },
          { lable: '状态', key: 'fenceStatus', width: '100px', align: 'center' }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      listLoading: true,
      simpleForm: {},
      activeIndex: 0,
      regions: getStorageByKey('regionsMap')
    }
  },
  computed: {
    // 省份下拉选项 跟随所选大区而变化
    provinceOptions() {
      if (this.regions && this.regions.length) {
        const currentBigArea = this.regions.filter(item => this.simpleForm.saleRegionName === item.bigAreaCode)
        const allProvince = this.regions.reduce((newArr, current) => {
          return newArr.concat(current.provinceList)
        }, [])
        if (currentBigArea.length) return unique_arr_by_key('provinceCode', currentBigArea[0].provinceList)
        return unique_arr_by_key('provinceCode', allProvince)
      } else {
        return []
      }
    },
    // 城市下拉选项 跟随所选省份而变化
    cityOptions() {
      const currentProvince = this.provinceOptions.filter(item => this.simpleForm.provinceCode === item.provinceCode)
      if (currentProvince.length) return currentProvince[0].cityDtoList
      const allCity = this.provinceOptions.reduce((newArr, current) => {
        return newArr.concat(current.cityDtoList)
      }, [])
      return allCity
    }
  },
  created() {
    this.queryTableList()
  },
  methods: {
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    toggleTbas(index) {
      this.activeIndex = index
      this.handelRest()
      this.queryTableList()
    },
    async queryTableList() {
      this.listLoading = true
      const { data } = await queryFenceList(this.formatParams())
      const items = data.data
      if (items.list && items.list.length) {
        items.list.forEach((row) => {
          const provinceAndCity = row.mainFenceAddress.split('/')
          row.provinceName = provinceAndCity[0]
          row.cityName = provinceAndCity[1]
        })
      }
      this.tables.data = items.list
      this.total = items.total
      this.listLoading = false
    },
    formatParams() {
      const params = { ...this.simpleForm, ...this.pages }
      params['fenceType'] = this.activeIndex
      return params
    },
    // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = ''
      }
    },
    toggleStatus(row) {
      switchFence({ id: row.id }).then(res => {
        this.queryTableList()
      })
    },
    handelEdit(row) {
      this.$emit('editFence', { id: row.id })
      // console.log(row)
    },
    handelDelete(row) {
      console.log(row)
      this.$confirm('此操作将删除电子围栏，您确认要继续吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = row.id
        deleteFence(params).then((res) => {
          console.log(res)
          this.queryTableList()
        })
        // this.$message({
        //   type: 'success',
        //   message: '已成功删除该电子围栏!'
        // })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}
</script>
<style>
.workorder-problem-desc {
  background-color: #303133;
  color: #fff;
  border-color: #303133;
}
</style>
<style lang="scss" scoped>
  ::v-deep .el-form-item .el-form-item__content{
            width: 200px;
          }
  .record-header, .record-title {
    font-family: 'PingFangSC-Semibold', 'PingFang SC Semibold', 'PingFang SC', sans-serif;
    font-weight: 650;
    font-style: normal;
  }
  .record-header {
    font-size: 22px;
    text-align: center;
    line-height: 50px;
  }
  .record-title{
    font-size: 14px;
    text-align: left;
    line-height: 30px;
    background: #f1f1ff;
    padding: 0 15px;
  }
  .serach-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    .search-inputs{
      width: 90%;
    }
  }
  .tool-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    line-height: 30px;
    .toggle-warning{
      font-weight: bold;
    }
    .toggle-alarm{
        display: flex;
        margin-bottom: 20px;
        font-size: 13px;
        font-family: 'PingFangSC-Regular', 'PingFang SC', sans-serif;
        font-weight: 400;
        font-style: normal;
        cursor: pointer;
        div{
          width: 103px;
          border: 1px solid rgba(121, 121, 121, 1);
          text-align: center;
        }
        :first-of-type{
          border-top-left-radius: 5px;
          border-bottom-left-radius: 5px;
          border-right: none
        }
        :last-of-type{
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
        }
        .isActive{
          color: #fff;
          background: rgba(5, 167, 171, 1);
          border-color: rgba(5, 167, 171, 1);
        }
    }
  }
</style>
